package com.guigu.work.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import io.seata.rm.datasource.DataSourceProxy;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * @ClassName:MybatisPlusConfig
 * @Description://TODO
 * @Author:taoLong
 * @Date:2021/11/9:17:05 星期二
 * @email:2391611102@qq.com or 2391611102qq@gmail.com
 */
@Configuration
@MapperScan("com.guigu.work.mapper")
public class MybatisPlusConfig {
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource() {
        return DruidDataSourceBuilder.create().build();
    }


    /**
     * 构造DataSource代理对象,替换原来的dataSource
     *
     * @param druidDataSource
     * @return
     */
    @Bean("dataSource")
    @Primary
    public DataSourceProxy dataSourceProxy(DataSource druidDataSource) {
        return new DataSourceProxy(druidDataSource);
    }


    @Bean
    public MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean(DataSourceProxy dataSourceProxy) throws IOException {
        MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
       /* mybatisSqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:com/guigu/order/mapper/xml/*.xml"));
        mybatisSqlSessionFactoryBean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:mybatis-config.xml"));
        mybatisSqlSessionFactoryBean.setTypeAliasesPackage("com.guigu.order.entity");*/
        mybatisSqlSessionFactoryBean.setDataSource(dataSourceProxy);
        PaginationInterceptor[] interceptor = {this.paginationInterceptor()};
        mybatisSqlSessionFactoryBean.setPlugins(interceptor);
        return mybatisSqlSessionFactoryBean;
    }

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}
